﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Fortunate.Common.Helper
{
    public class CopyHelper
    {


        public static D Mapper<D, S>(S s)
        {
            D d = Activator.CreateInstance<D>();
            try
            {
                var Types = s.GetType();//获得类型  
                var Typed = typeof(D);
                foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段  
                {
                    if (Typed.GetProperties().Where(p => p.Name.ToLower() == sp.Name.ToLower()).Count() > 0)
                    {
                        PropertyInfo dp = Typed.GetProperties().Where(p => p.Name.ToLower() == sp.Name.ToLower()).FirstOrDefault();
                        if (dp.PropertyType.FullName == sp.PropertyType.FullName)
                            dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性  
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return d;

        }


        public static D Set<D, S>(D d, S s)
        {
            if (s == null)
            {
                return d;
            }
            try
            {
                var Types = s.GetType();//获得类型  
                var Typed = d.GetType();
                foreach (PropertyInfo sp in Types.GetProperties())//获得类型的属性字段  
                {
                    if (Typed.GetProperties().Where(p => p.Name.ToLower() == sp.Name.ToLower()).Count() > 0)
                    {
                        PropertyInfo dp = Typed.GetProperties().Where(p => p.Name.ToLower().Contains(sp.Name.ToLower())).FirstOrDefault();
                        if (dp.PropertyType.FullName == sp.PropertyType.FullName)
                            dp.SetValue(d, sp.GetValue(s, null), null);//获得s对象属性的值复制给d对象的属性  
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return d;

        }



    }
}
